<template>
  <t-card :bordered="false">
    <!-- 容器 -->
    <div class="container">
      <t-space class="left" direction="vertical">
        <!-- 公司 -->
        <t-select
          v-model:value="searchParams.companyId"
          :options="companySimpleList"
          :keys="{ label: 'name', value: 'id' }"
          label="归属公司："
          filterable
          @change="handleChangeMaterial"
        />
        <t-tabs v-model:value="type" :list="list" @change="handleChangeMaterial" />
        <t-button
          v-permission="['system:budget-material-name:create']"
          @click="
            handleOpenLeftDialog('create', {
              companyId: searchParams.companyId,
              type: type
            })
          "
        >
          新建材料
        </t-button>
    
        <!-- 类目树 -->
        <t-tree
          :data="categoryTree"
          activable
          expand-on-click-node
          hover
          :keys="{ label: 'name', value: 'id' }"
          max-height="calc(100vh - 380px)"
          @click="handleClickCategoryTree"
        >
          <template #operations="{ node }">
            <t-space>
              <t-icon
                v-if="!node.data.parentId"
                v-permission="['system:budget-material-name:create']"
                name="add"
                @click="
                  handleOpenLeftDialog('create', {
                    companyId: searchParams.companyId,
                    type: type,
                    parentId: node.data.id,
                  })
                "
              />
              <t-icon
                v-permission="['system:budget-material-name:update']"
                name="edit"
                @click="handleOpenLeftDialog('update', { id: node.data.id })"
              />
              <t-popconfirm
                content="确认要删除该项吗？"
                @confirm="handleDeleteLeft(node.data)"
              >
                <t-icon v-permission="['system:budget-material-name:delete']" name="delete" />
              </t-popconfirm>
            </t-space>
          </template>
        </t-tree>
      </t-space>
      <t-divider class="divider" layout="vertical" />
      <div v-show="searchParams.materialId" class="right">
        <!-- 自定义搜索 -->
        <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleInitTable">
          <t-col :span="4">
            <t-form-item label="材料名称" name="name">
              <t-input v-model:value="params.name" clearable placeholder="" />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="品牌名称" name="brandName">
              <t-input v-model:value="params.brandName" clearable placeholder="" />
            </t-form-item>
          </t-col>
        </custom-search>
        <!-- 自定义表格 -->
        <custom-table
          ref="customTableRef"
          row-key="id"
          :columns="columns"
          :api="materialLibraryCRUD.page"
          column-controller-key="materialLibraryList"
        >
          <template #topContent>
            <div style="margin-bottom: var(--td-comp-margin-xxl)">
              <t-button
                v-permission="['system:budget-material-data:create']"
                @click="
                  handleOpenDialog('create', {
                    companyId: searchParams.companyId,
                    materialDataType:type,
                    materialId: searchParams.materialId,
                    fileUrlList: []
                  })
                "
              >
                新建材料
              </t-button>
              <import-material :material-id="searchParams.materialId" @request-success="handleDialogRequestSuccess"/>
            </div>
          </template>
          <template #materialDataType="{ row }">
            {{ row.materialDataType=='1'?'主材':row.materialDataType=='2'?'辅材':'' }}
          </template>
          <template #unit="{ row }">
            {{ dictionaryStore.analysis('unit', row.unit) }}
          </template>
          <template #fileUrl="{ row }">
            <image-viewer v-if="row.fileUrl" :images="[row.fileUrl]" width="80px" height="80px" />
          </template>
          <template #createTime="{ row }">
            {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template #operation="{ row }">
            <t-space>
              <t-link
                v-permission="['system:budget-material-data:query']"
                theme="primary"
                @click="handleOpenDialog('read', { id: row.id })"
              >
                详情
              </t-link>
              <t-link
                v-permission="['system:budget-material-data:update']"
                theme="primary"
                @click="handleOpenDialog('update', { id: row.id })"
              >
                编辑
              </t-link>
              <t-popconfirm
                content="确认要删除该项吗？"
                @confirm="handleDelete({ id: row.id })"
              >
                <t-link v-permission="['system:budget-material-data:delete']" theme="danger"> 删除 </t-link>
              </t-popconfirm>
            </t-space>
          </template>
        </custom-table>
      </div>
      <t-empty v-show="!searchParams.materialId" class="right" title="请先选择主材料" style="margin-top: 30vh" />
    </div>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="materialLibraryCRUD"
      header="*材料"
       :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      <!-- <t-form-item label="材料类型" name="materialDataType" :rules="[{ required: true, message: '请选择材料类型' }]">
        <t-select
          v-model:value="formData.materialDataType"
          :options="list"
          placeholder="请选择材料类型"
          clearable
          filterable
          readonly
          @clear="formData.materialDataType = null"
        />
      </t-form-item> -->
        <t-form-item label="封面图" name="fileUrl" :rules="[{ required: false, message: '请上传封面图' }]">
          <upload 
            v-model:files="formData.fileUrlList" 
            accept="image/*" 
            theme="image" 
            :disabled="readonly"
            @change="
                (value) => {
                  formData.fileUrl = value[0]?.url;
                }
              "
            />
        </t-form-item>
        <t-form-item label="材料名称" name="name" :rules="[{ required: true, message: '请输入材料名称' }]">
          <t-input v-model:value="formData.name" placeholder="请输入材料名称" clearable :readonly="readonly" />
        </t-form-item>
        <t-form-item label="品牌名称" name="brandName" :rules="[{ required: true, message: '请输入品牌名称' }]">
          <t-input v-model:value="formData.brandName" placeholder="请输入品牌名称" clearable :readonly="readonly" />
        </t-form-item>
        
        <t-form-item label="型号" name="model" :rules="[{ required: false, message: '请输入型号' }]">
          <t-input v-model:value="formData.model" placeholder="请输入型号" clearable :readonly="readonly" />
        </t-form-item>
        <t-form-item label="规格" name="specifications" :rules="[{ required: false, message: '请输入规格' }]">
          <t-input v-model:value="formData.specifications" placeholder="请输入规格" clearable :readonly="readonly" />
        </t-form-item>
        <t-form-item label="单位" name="unit" :rules="[{ required: true, message: '请选择单位' }]">
          <t-select
            v-model:value="formData.unit"
            :options="dictionaryStore.get('unit')"
            placeholder="请选择单位"
            clearable
            filterable
            :readonly="readonly"
            @clear="formData.unit = null"
          />
          
        </t-form-item>
   
        <t-form-item label="成本价(元)" name="costPrice" :rules="[{ required: true, message: '请输入成本价' }]">
          <t-input-number
            v-model:value="formData.costPrice"
            :decimal-places="2"
            min="0"
            :allow-input-over-limit="false"
            placeholder="请输入成本价"
            :readonly="readonly"
            style="width: 100%"
          />
        </t-form-item>
        <t-form-item label="售价(元)" name="sellingPrice" :rules="[{ required: true, message: '请输入售价' }]">
          <t-input-number
            v-model:value="formData.sellingPrice"
            :decimal-places="2"
            min="0"
            :allow-input-over-limit="false"
            placeholder="请输入售价"
            :readonly="readonly"
            style="width: 100%"
          />
        </t-form-item>
        <t-form-item label="备注" name="remark">
          <t-textarea v-model:value="formData.remark" placeholder="请输入备注" :readonly="readonly" />
        </t-form-item>

    </custom-dialog>

    <!-- 左侧新增材料对话框 -->
    <custom-dialog
      ref="customDialogLeftRef"
      v-slot="{ formData, readonly }"
      :api-map="materialLibraryNameCRUD"
      header="*材料"
      @request-success="handleDialogRequestSuccessLeft"
    >
      <t-form-item label="材料类型" name="type" :rules="[{ required: true, message: '请选择材料类型' }]">
        <t-select
          v-model:value="formData.type"
          :options="list"
          placeholder="请选择材料类型"
          clearable
          filterable
          readonly
          @clear="formData.type = null"
        />
      </t-form-item>

        <t-form-item label="材料名称" name="name" :rules="[{ required: true, message: '请输入材料名称' }]">
          <t-input v-model:value="formData.name" placeholder="请输入材料名称" clearable :readonly="readonly" />
        </t-form-item>
        

    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'MaterialLibrary',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import { onMounted, reactive, ref, useTemplateRef } from 'vue';

import { materialLibraryNameCRUD, materialLibraryCRUD } from '@/api/budget/material-library';
import { getCompanyList } from '@/api/system/dept';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import ImageViewer from '@/components/image-viewer/index.vue';
import Upload from '@/components/upload/index.vue';
import ImportMaterial from './components/ImportMaterial.vue';
import { useDictionaryStore } from '@/store';
import listToTree from '@/utils/listToTree';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 默认材料类型
const type = ref('1')
// tab
const list = ref([
  { label: '主材', value: '1' },
  { label: '辅材', value: '2' },
])
// 搜索参数
const searchParams = reactive({
  companyId: null,
  materialId: null,
});
// 公司精简列表
const companySimpleList = ref([]);
// 处理获取公司精简列表
const handleGetCompanySimpleList = async () => {
  return getCompanyList().then((data) => {
    companySimpleList.value = data;
    searchParams.companyId = data[0].id;
  });
};
// 类目列表
const categoryList = ref([]);
// 类目树
const categoryTree = ref([]);
// 处理获取类目
const handleGetCategory = () => {
  const params = {
    companyId: searchParams.companyId,
    type: type.value,
    pageSize: -1,
  };
  materialLibraryNameCRUD.page(params).then((data) => {
    categoryList.value = data.list;
    categoryTree.value = listToTree(data.list);
  });
};
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'fileUrl', title: '封面图' },
  { colKey: 'name', title: '材料名称' },
  { colKey: 'unit', title: '单位' },
  { colKey: 'brandName', title: '品牌名称' },
  { colKey: 'specifications', title: '规格' },
  { colKey: 'materialDataType', title: '材料类型' },
  // { colKey: 'materialNo', title: '材料编码' },
  { colKey: 'model', title: '型号' },
  { colKey: 'costPrice', title: '成本价(元)' },
  { colKey: 'sellingPrice', title: '售价(元)' },
  { colKey: 'remark', title: '备注' },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 150, fixed: 'right' },
];
// 处理初始化表格
const handleInitTable = () => {
  const params = {
    ...customSearchRef.value.params,
    companyId: searchParams.companyId,
    type: type.value,
    materialId: searchParams.materialId,
  };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(async () => {
  await handleGetCompanySimpleList();
  handleGetCategory();
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 自定义材料左侧对话框ref
const customDialogLeftRef = useTemplateRef('customDialogLeftRef');
// 处理打开对话框
const handleOpenLeftDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogLeftRef.value.open(mode, params);
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  // 图片
  params.fileUrlList = [];
  if (params.fileUrl) params.fileUrlList.push({ url: params.fileUrl });
  
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理对话框请求成功
const handleDialogRequestSuccessLeft = (result: Record<string, any>) => {
  handleGetCategory();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  materialLibraryCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理删除左侧
const handleDeleteLeft = (params: Record<string, any>) => {
  console.log(params,'p');
  if(params.children) {
    MessagePlugin.error('有子节点不允许删除');
  } else {
    materialLibraryNameCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功'); 
      handleGetCategory();
      searchParams.materialId = null;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
  }
 
};
// 处理点击类目树
const handleClickCategoryTree = ({ node }: { node: TreeNodeModel }) => {
    if(node.data.parentId) {
      searchParams.materialId = node.value;
      handleInitTable();
    }
};
// 左侧主材、辅材切换
const handleChangeMaterial = () => {
  handleGetCategory();
  searchParams.materialId = null;
}
</script>

<style lang="less" scoped>
// 容器
.container {
  display: flex;
  justify-content: center;
  align-items: flex-start;

  .left {
    width: 300px;
    height: calc(100vh - 236px);
    overflow: hidden;

    :deep(.t-tree) {
      padding-right: 8px;

      &::-webkit-scrollbar {
        width: 8px;
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 6px;
        border: 2px solid transparent;
        background-clip: content-box;
        background-color: var(--td-scrollbar-color);
      }
    }
  }

  .divider {
    height: calc(100vh - 236px);
  }

  .right {
    width: calc(100% - 325px);
  }
  :deep(.t-tabs__nav-item) {
    flex: 1;
    justify-content: center;
  }
  :deep(.t-tabs__nav-wrap) {
    width: 100%;
  }
}

</style>
